﻿
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Commodity</title>
    <link href="~/layui/css/layui.css" rel="stylesheet" />
    <style>
        .layui-table-body .layui-table-cell {
            height: 50px;
            line-height: 50px;
        }
        .layui-unselect dl {  @*layui 下拉框高度*@
            max-height: 200px;
        }
    </style>
</head>
<body style="min-width:800px;">
    <div style="padding:10px;">
        <div class="layui-row">
            <form class="layui-form" style="margin-top:10px;">
                <div class="layui-form-item">
                    <label class="layui-form-label" style="width:45px;">分类</label>
                    <div class="layui-input-inline" style="width:100px;">
                        <select id="big" lay-filter="big"></select>
                    </div>
                    <div class="layui-input-inline" style="width:100px;">
                        <select id="centre" lay-filter="centre"></select>
                    </div>
                    <div class="layui-input-inline" style="width:100px;">
                        <select id="little" lay-filter="little"></select>
                    </div>
                    <div class="layui-input-inline" style="width:100px;">
                        <input type="text" name="title" id="shopName" placeholder="商品名称" autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-input-inline">
                        <input type="button" class="layui-btn" id="search" value="搜索" />
                    </div>
                </div>
            </form>
        </div>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
                <button class="layui-btn layui-btn-sm" lay-event="delete">删除</button>
                <button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>
            </div>
        </script>
        <table id="demo" lay-filter="test" style="width: auto;"></table>
    </div>


    

    @*用于弹出添加、编辑框*@
    <form class="layui-form" action="" id="pro" lay-filter="proForm" style="display:none;height:400px;">
        <input type="text" hidden="hidden" name="proId" id="proId" value="0" />
        <input type="text" hidden="hidden" name="proImage" id="proImage" value="0" />
        <div class="layui-form-item">
            <label class="layui-form-label">名称：</label>
            <div class="layui-input-block">
                <input type="text" Id="proName" name="proName" required lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">图片：</label>
            <div class="layui-input-block">
                <img id="proImg" name="proImg" style="width:70px;height:70px;" />
                <button type="button" class="layui-btn" id="proUpload">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">分类：</label>
            <div class="layui-input-inline" style="width:100px;">
                <select id="proBig" lay-filter="proBig" name="proBig"></select>
            </div>
            <div class="layui-input-inline" style="width:100px;">
                <select id="proCentre" lay-filter="proCentre" name="proCentre"></select>
            </div>
            <div class="layui-input-inline" style="width:100px;">
                <select id="proLittle" lay-filter="proLittle" required lay-verify="required" name="proLittle"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">金额：</label>
            <div class="layui-input-block">
                <input type="text" Id="proPrice" name="proPrice" required lay-verify="required" placeholder="请输入金额" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注：</label>
            <div class="layui-input-block">
                <textarea Id="proRemark" name="proRemark" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>
    </form>




    <script src="~/js/jquery-2.2.4.min.js"></script>
    <script src="~/layui/layui.js"></script>
    <script src="~/layui/lay/modules/upload.js"></script>
    <script type="text/javascript">
        var typeData;
    </script>
    <script>
        layui.use('table', function () {
            var table = layui.table;
            var upload = layui.upload;
            var Id = '0';
            var listUrl = '/shop/CommodityList';
            var tableData;
            var pickData;
            //第一个实例
            table.render({
                elem: '#demo'
                , toolbar: '#toolbarDemo'
                , height: 500
                , url: listUrl //数据接口
                , page: true //开启分页
                , limit: 10
                , id: 'idTest'//便于重载表格
                , cols: [[ //表头
                    { type: 'checkbox' }
                    , { field: 'id', title: 'ID', width: '5%', sort: true }
                    , { field: 'name', title: '名称', width: '10%' }
                    , {
                        field: 'image', title: '图片', width: '10%', height: '150px', sort: false, templet: function (d) {
                            return '<img class="tooltip" src="' + d.image + '"  alt="' + d.name + '" />'
                        }
                    }
                    , { field: 'typeName', title: '类型', width: '10%' }
                    , { field: 'price', title: '金额', width: '10%', sort: true }
                    , { field: 'shopNum', title: '交易', width: '8%', sort: true }
                    , { field: 'comment', title: '评论', width: '8%', sort: true }
                    , { field: 'remark', title: '备注' }
                    , { field: 'type', title: '隐藏', hide: true }
                ]]
                , parseData: function (res) { //res 即为原始返回的数据
                    tableData = res.data;
                }
            });
            table.on('row(test)', function (obj) {
                //console.log(obj.tr) //得到当前行元素对象
                //console.log(obj.data) //得到当前行数据
                $(".layui-table-body tr").each(function (ii, vv) {
                    //ii 指第几个元素的序列号。
                    //vv 指遍历得到的元素。
                    $(this).css("background-color", "#fff");
                });
                $(obj.tr.selector).css("background-color","antiquewhite");
                pickData = obj.data;
            });



            //监听工具栏
            table.on('toolbar(test)', function (obj) {
                console.log(obj);
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'add':
                        prolittle = 0;
                        layer.msg(obj.event, { time: 400 });
                        $('#pro')[0].reset();
                        //if (little == 0) {
                        //    layer.msg('请在页面内选择好分类，再点添加。', { time: 1100 }); return;
                        //}
                        $("#proLittle,#proBig,#proCentre").empty(); form.render('select'); CommodityType(false);
                        $("#proImg").attr("src", "");
                        layer.prompt({
                            title: obj.event,
                            anim: 1,
                            content: $("#pro"),
                            yes: function (index, layero) {
                                if (prolittle == 0) {
                                    layer.msg('请正确选择分类！', { time: 1000 });  return;
                                }
                                $.ajax({
                                    url: "/shop/CommodityAdd",
                                    data: { 'Name': $('#proName').val(), 'Image': $('#proImage').val(), 'Type': prolittle, 'Price': $('#proPrice').val(), 'Remark': $('#proRemark').val(), 'base64Str': base64Str },
                                    type: "post",
                                    success: function (res) {
                                        layer.msg(res.msg, { time: 1000 });
                                        if (res.success) {
                                            table.reload('idTest', {
                                                page: { curr: 1 }
                                                //url: listUrl
                                                , where: { big, centre, little, shopName } //设定异步数据接口的额外参数
                                            });
                                            layer.close(index);//如果设定了yes回调，需进行手工关闭
                                        }
                                    }
                                });
                            }
                        });
                        break;
                    case 'delete':
                        layer.msg(obj.event, { time: 400 });
                        if (Id.length <= 2) {
                            layer.msg('请选择要删除的信息！', { time: 1000 }); return;
                        }
                        layer.confirm('确定删除ID为' + Id.replace('0,', '') + '的' + '' + '整条信息吗？', {
                            btn: ['确定', '取消'],
                            btn1: function (index) {
                                $.ajax({
                                    url: "/shop/CommodityDelete",
                                    data: { 'Id': Id.replace('0,', '') },
                                    type: "get",
                                    success: function (res) {
                                        layer.msg(res.msg, { time: 1000 });
                                        if (res.success) {
                                            table.reload('idTest', {
                                                page: { curr: $(".layui-laypage-skip input").eq(0).val() }
                                                //url: listUrl
                                                , where: { big, centre, little, shopName } //设定异步数据接口的额外参数
                                            });
                                            console.log(tableData);
                                            layer.close(index);//如果设定了yes回调，需进行手工关闭
                                        }
                                    }
                                });
                            },
                            btn2: function (index) {
                                layer.msg('取消', { time: 400 }); layer.close(index);
                            }
                        });
                        break;
                    case 'update':
                        console.log(pickData);
                        if (pickData == undefined || pickData.length == 0) {
                            layer.msg('请选择要编辑的信息！', { time: 1000 }); return;
                        }
                        prolittle = pickData.type;
                        $('#pro')[0].reset();
                        $("#proLittle,#proBig,#proCentre").empty(); form.render('select'); CommodityType(false);

                        var proCentre = JSON.parse(JSON.stringify(typeData.filter((item) => { return item.id == pickData.type; })))[0].parentId;
                        var proBig = JSON.parse(JSON.stringify(typeData.filter((item) => { return item.id == proCentre; })))[0].parentId;
                        $('#proBig').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + proBig + ']').click();
                        $('#proCentre').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + proCentre + ']').click();
                        $('#proLittle').siblings("div.layui-form-select").find('dl').find('dd[lay-value=' + pickData.type + ']').click();

                        form.val("proForm", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                            "proName": pickData.name // "name": "value"
                            , "proImage": pickData.image
                            , "proPrice": pickData.price
                            , "proRemark": pickData.remark
                            , "proImg": pickData.image
                            , "proId": pickData.id
                        });
                        $("#proImg").attr("src", pickData.image);
                        layer.msg(obj.event, { time: 400 });
                        layer.prompt({
                            title: obj.event,
                            anim: 1,
                            content: $("#pro"),
                            yes: function (index, layero) {
                                if (prolittle == 0) {
                                    layer.msg('请正确选择分类！', { time: 1000 });  return;
                                }
                                if ($('#proName').val() == "" || $('#proPrice').val() == "" || $('#proId').val() == "") {
                                    layer.msg('不能为空！', { time: 1000 }); return;
                                }
                                $.ajax({
                                    url: "/shop/CommodityUpdate",
                                    data: { 'Name': $('#proName').val(), 'Image': $('#proImage').val(), 'Type': prolittle, 'Price': $('#proPrice').val(), 'Remark': $('#proRemark').val(), 'Id': $('#proId').val(), 'base64Str': base64Str },
                                    type: "post",
                                    success: function (res) {
                                        layer.msg(res.msg, { time: 1000 });
                                        if (res.success) {
                                            table.reload('idTest', {
                                                page: { curr: $(".layui-laypage-skip input").eq(0).val() }
                                                //url: listUrl
                                                , where: { big, centre, little, shopName } //设定异步数据接口的额外参数
                                            });
                                            layer.close(index);//如果设定了yes回调，需进行手工关闭
                                        }
                                    }
                                });
                            }
                        });
                        break;
                };
            });
            //监听复选框
            table.on('checkbox(test)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                console.log(obj); //所在行的所有相关数据
                if (obj.checked) {
                    Id += ',' + obj.data.id;
                }
                else {
                    Id = Id.replace(',' + obj.data.id, '');
                }
            });


            var form = layui.form;
            var big = 0;
            var centre = 0;
            var little = 0;
            var shopName = "";
            form.on('select(big)', function (data) {
                if (data.value == 0) return;
                big = data.value;
                var an = typeData.filter((item) => {
                    return item.parentId == big;
                });
                var select = JSON.parse(JSON.stringify(an));
                var selectStr = ('<option value="' + 0 + '">' + '全部' + '</option>');
                for (var i = 0; i < select.length; i++) {
                    var node = ('<option value="' + select[i].id + '">' + select[i].name + '</option>');
                    selectStr += node;
                }
                $("#centre").html(selectStr);
                $("#little").empty();
                form.render('select'); //刷新select选择框渲染
            });
            form.on('select(centre)', function (data) {
                if (data.value == 0) return;
                centre = data.value;
                var an = typeData.filter((item) => {
                    return item.parentId == centre;
                });
                var select = JSON.parse(JSON.stringify(an));
                var selectStr = ('<option value="' + 0 + '">' + '全部' + '</option>');
                for (var i = 0; i < select.length; i++) {
                    var node = ('<option value="' + select[i].id + '">' + select[i].name + '</option>');
                    selectStr += node;
                }
                $("#little").html(selectStr);
                form.render('select'); //刷新select选择框渲染
            });
            form.on('select(little)', function (data) {
                little = data.value;
            });
            function CommodityType(flag) {
                var an = typeData.filter((item) => {
                    return item.parentId == 0;
                });
                var select = JSON.parse(JSON.stringify(an));
                var selectStr = "";
                selectStr += ('<option value="' + 0 + '">' + '全部' + '</option>');
                for (var i = 0; i < select.length; i++) {
                    var node = ('<option value="' + select[i].id + '">' + select[i].name + '</option>');
                    selectStr += node;
                }
                if (flag) $("#big").html(selectStr);
                $("#proBig").html(selectStr);
                form.render('select'); //刷新select选择框渲染
            }
            //商品分类
            $.get("/Shop/CommodityType", function (res) {
                typeData = res.data;
                CommodityType(true);
            });
            $("#shopName").blur(function () {
                shopName = $(this).val();
            });
            //搜索
            $("#search").click(function () {
                table.reload('idTest', {
                    page: { curr: 1 }
                    //url: listUrl
                    , where: { big, centre, little, shopName } //设定异步数据接口的额外参数
                });
            });



            // 添加 、 编辑  按钮  所需要的下拉框选
            var prolittle = 0;
            form.on('select(proBig)', function (data) {
                if (data.value == 0) return;
                var an = typeData.filter((item) => {
                    return item.parentId == data.value;
                });
                var select = JSON.parse(JSON.stringify(an));
                var selectStr = ('<option value="' + 0 + '">' + '全部' + '</option>');
                for (var i = 0; i < select.length; i++) {
                    var node = ('<option value="' + select[i].id + '">' + select[i].name + '</option>');
                    selectStr += node;
                }
                $("#proCentre").html(selectStr);
                form.render('select'); //刷新select选择框渲染
            });
            form.on('select(proCentre)', function (data) {
                if (data.value == 0) return;
                var an = typeData.filter((item) => {
                    return item.parentId == data.value;
                });
                var select = JSON.parse(JSON.stringify(an));
                var selectStr = ('<option value="' + 0 + '">' + '全部' + '</option>');
                for (var i = 0; i < select.length; i++) {
                    var node = ('<option value="' + select[i].id + '">' + select[i].name + '</option>');
                    selectStr += node;
                }
                $("#proLittle").html(selectStr);
                form.render('select'); //刷新select选择框渲染
            });
            form.on('select(proLittle)', function (data) {
                prolittle = data.value;
            });

            var base64Str = '';
            //上传图片实例
            upload.render({
                elem: '#proUpload' //绑定元素
                , url: '/shop/CommodityUpdate' //上传接口
                , acceptMime: 'image/*' //只筛选图片
                , auto: false //选择文件后不自动上传
                , size: 1024 * 5 //限定大小
                , choose: function (obj) {
                    //将每次选择的文件追加到文件队列
                    var files = obj.pushFile();

                    //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                    obj.preview(function (index, file, result) {
                        console.log(index); //得到文件索引
                        console.log(file); //得到文件对象
                        console.log(result); //得到文件base64编码，比如图片
                        $("#proImg").attr("src", result);
                        base64Str = result;
                    });
                }
            });
            //图片放大
            $(document).on('mouseover', '.tooltip', function (e) {
                var e = event || window.event;
                var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
                var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
                var x = e.pageX || e.clientX + scrollX;
                var y = e.pageY || e.clientY + scrollY;
                this.myTitle = this.title;
                this.title = "";
                var imgTitle = this.myTitle ? "<br/>" + this.myTitle : "";
                var tooltip = "<div id='tooltip'><img src='" + this.src + "' alt='产品预览图' style='max-width:250px;max-height:250px;'/>" + imgTitle + "<\/div>"; //创建 div 元素
                $("body").append(tooltip);    //把它追加到文档中
                $("#tooltip")
                    .css({
                        "top": "40%",
                        "left": "40%",
                        "position": "absolute"
                    }).show("fast");      //设置x坐标和y坐标，并且显示
            });

            $(document).on('mouseout', '.tooltip', function (e) {
                this.title = this.myTitle;
                $("#tooltip").remove();     //移除
            });

            $(document).on('mousemove', '.tooltip', function (e) {
                $("#tooltip")
                    .css({
                        "top": "40%",
                        "left": "40%"
                    });
            });
        });
    </script>
</body>
</html>
